// 学生管理系统JavaScript
$(document).ready(function() {
    // 初始化页面
    loadStudents(1);
    
    // 绑定事件
    bindEvents();
});

// 全局变量
let currentPage = 1;
let pageSize = 10;
let totalPages = 0;
let currentSort = { field: '', order: '' }; // 当前排序
let selectedStudents = new Set(); // 选中的学生ID集合

// 绑定事件
function bindEvents() {
    // 搜索按钮事件
    $('#searchBtn').click(function() {
        searchStudents();
    });
    
    // 重置按钮事件
    $('#resetBtn').click(function() {
        resetSearch();
    });
    
    // 新增按钮事件
    $('#addBtn').click(function() {
        showAddModal();
    });
    
    // 模态框关闭事件
    $('.close, .modal').click(function(e) {
        if (e.target === this) {
            closeModal();
        }
    });
    
    // 表单提交事件
    $('#studentForm').submit(function(e) {
        e.preventDefault();
        saveStudent();
    });
    
    // 回车搜索
    $('.search-input').keypress(function(e) {
        if (e.which === 13) {
            searchStudents();
        }
    });
    
    // 排序按钮事件
    $(document).on('click', '.sort-btn', function() {
        const field = $(this).data('field');
        const order = $(this).data('order');
        sortStudents(field, order);
    });
    
    // 全选复选框事件
    $('#selectAll').change(function() {
        const isChecked = $(this).prop('checked');
        $('.student-checkbox').prop('checked', isChecked);
        if (isChecked) {
            $('.student-checkbox').each(function() {
                selectedStudents.add(parseInt($(this).val()));
            });
        } else {
            selectedStudents.clear();
        }
        updateBatchToolbar();
    });
    
    // 单个复选框事件
    $(document).on('change', '.student-checkbox', function() {
        const studentId = parseInt($(this).val());
        if ($(this).prop('checked')) {
            selectedStudents.add(studentId);
        } else {
            selectedStudents.delete(studentId);
            $('#selectAll').prop('checked', false);
        }
        updateBatchToolbar();
    });
    
    // 批量删除事件
    $('#batchDeleteBtn').click(function() {
        batchDeleteStudents();
    });
}

// 排序功能
function sortStudents(field, order) {
    currentSort = { field, order };
    
    // 更新排序按钮样式
    $('.sort-btn').removeClass('active');
    $(`.sort-btn[data-field="${field}"][data-order="${order}"]`).addClass('active');
    
    // 重新加载数据
    loadStudents(currentPage);
}

// 加载学生列表 - 更新以支持排序
function loadStudents(page = 1, name = '', major = '', classNumber = '') {
    currentPage = page;
    showLoading(true);
    
    const requestData = {
        page: page,
        size: pageSize,
        name: name,
        major: major,
        classNumber: classNumber
    };
    
    // 添加排序参数
    if (currentSort.field) {
        requestData.sortField = currentSort.field;
        requestData.sortOrder = currentSort.order;
    }
    
    $.ajax({
        url: '/api/students',
        type: 'GET',
        data: requestData,
        success: function(response) {
            if (response.code === 200) {
                renderStudentTable(response.data.records);
                renderPagination(response.data);
                // 清空选择状态
                selectedStudents.clear();
                $('#selectAll').prop('checked', false);
                updateBatchToolbar();
            } else {
                showAlert('加载数据失败：' + response.message, 'danger');
            }
            showLoading(false);
        },
        error: function() {
            showAlert('网络错误，请稍后重试', 'danger');
            showLoading(false);
        }
    });
}

// 渲染学生表格 - 更新以支持复选框
function renderStudentTable(students) {
    const tbody = $('#studentTableBody');
    tbody.empty();
    
    if (!students || students.length === 0) {
        tbody.append(`
            <tr>
                <td colspan="10" style="text-align: center; padding: 2rem; color: #999;">
                    暂无数据
                </td>
            </tr>
        `);
        return;
    }
    
    students.forEach(function(student) {
        const row = `
            <tr>
                <td>
                    <input type="checkbox" class="student-checkbox" value="${student.id}">
                </td>
                <td>${student.id}</td>
                <td>
                    <a href="/student/profile?id=${student.id}" class="student-name-link">
                        ${student.name}
                    </a>
                </td>
                <td>${student.gender}</td>
                <td>${student.birthDate || '-'}</td>
                <td>${student.major}</td>
                <td>${student.classNumber}</td>
                <td>${student.enrollmentDate || '-'}</td>
                <td>${student.address || '-'}</td>
                <td>
                    <button class="btn btn-info btn-sm" onclick="viewStudent(${student.id})" title="查看详情">
                        查看
                    </button>
                    <button class="btn btn-warning btn-sm" onclick="editStudent(${student.id})">
                        编辑
                    </button>
                    <button class="btn btn-danger btn-sm" onclick="deleteStudent(${student.id})">
                        删除
                    </button>
                </td>
            </tr>
        `;
        tbody.append(row);
    });
}

// 新增查看学生详情函数
function viewStudent(studentId) {
    window.location.href = `/student/profile?id=${studentId}`;
}

// 更新批量操作工具栏
function updateBatchToolbar() {
    const count = selectedStudents.size;
    $('#selectedCount').text(`已选择 ${count} 项`);
    
    if (count > 0) {
        $('#batchToolbar').show();
    } else {
        $('#batchToolbar').hide();
    }
}

// 批量删除功能
// 在现有代码基础上添加导出功能

// 绑定导出按钮事件
$('#exportBtn').click(function() {
    exportStudents();
});

// 导出学生数据
function exportStudents() {
    const name = $('#searchName').val();
    const major = $('#searchMajor').val();
    const classNumber = $('#searchClassNumber').val();
    
    // 构建查询参数
    const params = new URLSearchParams();
    if (name) params.append('name', name);
    if (major) params.append('major', major);
    if (classNumber) params.append('classNumber', classNumber);
    
    // 创建下载链接
    const url = '/api/students/export?' + params.toString();
    
    // 显示加载状态
    $('#exportBtn').addClass('loading').prop('disabled', true);
    
    // 创建隐藏的下载链接
    const link = document.createElement('a');
    link.href = url;
    link.download = '学生信息.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // 恢复按钮状态
    setTimeout(() => {
        $('#exportBtn').removeClass('loading').prop('disabled', false);
        showAlert('导出成功', 'success');
    }, 1000);
}

// 增强的批量删除功能
function batchDeleteStudents() {
    if (selectedStudents.size === 0) {
        showAlert('请先选择要删除的学生', 'warning');
        return;
    }
    
    if (!confirm(`确定要删除选中的 ${selectedStudents.size} 个学生吗？此操作不可恢复！`)) {
        return;
    }
    
    const studentIds = Array.from(selectedStudents);
    
    $.ajax({
        url: '/api/students/batch',
        type: 'DELETE',
        contentType: 'application/json',
        data: JSON.stringify(studentIds),
        success: function(response) {
            if (response.code === 200) {
                showAlert(response.message, 'success');
                loadStudents(currentPage);
                selectedStudents.clear();
                updateBatchToolbar();
            } else {
                showAlert(response.message, 'danger');
            }
        },
        error: function(xhr) {
            const response = JSON.parse(xhr.responseText);
            showAlert(response.message || '批量删除失败', 'danger');
        }
    });
}

// 渲染分页
function renderPagination(pageData) {
    const pagination = $('#pagination');
    pagination.empty();
    
    totalPages = pageData.pages;
    const current = pageData.current;
    
    // 上一页
    const prevDisabled = current <= 1 ? 'disabled' : '';
    pagination.append(`
        <button ${prevDisabled} onclick="loadStudents(${current - 1})">
            上一页
        </button>
    `);
    
    // 页码
    const startPage = Math.max(1, current - 2);
    const endPage = Math.min(totalPages, current + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        const activeClass = i === current ? 'active' : '';
        pagination.append(`
            <button class="${activeClass}" onclick="loadStudents(${i})">
                ${i}
            </button>
        `);
    }
    
    // 下一页
    const nextDisabled = current >= totalPages ? 'disabled' : '';
    pagination.append(`
        <button ${nextDisabled} onclick="loadStudents(${current + 1})">
            下一页
        </button>
    `);
    
    // 显示总数信息
    $('#pageInfo').text(`共 ${pageData.total} 条记录，第 ${current} / ${totalPages} 页`);
}

// 搜索学生
function searchStudents() {
    const name = $('#searchName').val().trim();
    const major = $('#searchMajor').val().trim();
    const classNumber = $('#searchClass').val().trim();
    
    loadStudents(1, name, major, classNumber);
}

// 重置搜索
function resetSearch() {
    $('#searchName').val('');
    $('#searchMajor').val('');
    $('#searchClass').val('');
    loadStudents(1);
}

// 显示新增模态框
function showAddModal() {
    $('#modalTitle').text('新增学生');
    $('#studentForm')[0].reset();
    $('#studentId').val('');
    $('#studentModal').show();
}

// 编辑学生
function editStudent(id) {
    $.ajax({
        url: `/api/students/${id}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const student = response.data;
                $('#modalTitle').text('编辑学生');
                $('#studentId').val(student.id);
                $('#studentName').val(student.name);
                $('#studentGender').val(student.gender);
                $('#studentBirthDate').val(student.birthDate);
                $('#studentMajor').val(student.major);
                $('#studentClassNumber').val(student.classNumber);
                $('#studentEnrollmentDate').val(student.enrollmentDate);
                $('#studentAddress').val(student.address);
                $('#studentModal').show();
            } else {
                showAlert('获取学生信息失败：' + response.message, 'danger');
            }
        },
        error: function() {
            showAlert('网络错误，请稍后重试', 'danger');
        }
    });
}

// 保存学生
// 在现有代码基础上添加验证功能

// 表单验证规则
const validationRules = {
    name: {
        required: true,
        minLength: 2,
        maxLength: 20,
        pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
        message: '姓名必须是2-20个字符的中文或英文'
    },
    gender: {
        required: true,
        pattern: /^(男|女)$/,
        message: '请选择性别'
    },
    major: {
        required: true,
        minLength: 2,
        maxLength: 50,
        message: '专业名称必须是2-50个字符'
    },
    classNumber: {
        required: true,
        pattern: /^[A-Za-z0-9]{2,20}$/,
        message: '班级编号格式不正确（2-20位字母数字）'
    },
    phone: {
        required: false,
        pattern: /^1[3-9]\d{9}$/,
        message: '手机号格式不正确'
    },
    email: {
        required: false,
        pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
        message: '邮箱格式不正确'
    }
};

// 表单验证函数
function validateForm() {
    const form = document.getElementById('studentForm');
    const formData = new FormData(form);
    const errors = [];
    
    // 清除之前的错误提示
    $('.error-message').remove();
    $('.form-control').removeClass('error');
    
    // 验证每个字段
    Object.keys(validationRules).forEach(field => {
        const value = document.getElementById('student' + field.charAt(0).toUpperCase() + field.slice(1)).value;
        const rule = validationRules[field];
        
        if (rule.required && (!value || value.trim() === '')) {
            errors.push({ field, message: rule.message });
            return;
        }
        
        if (value && rule.pattern && !rule.pattern.test(value)) {
            errors.push({ field, message: rule.message });
            return;
        }
        
        if (value && rule.minLength && value.length < rule.minLength) {
            errors.push({ field, message: rule.message });
            return;
        }
        
        if (value && rule.maxLength && value.length > rule.maxLength) {
            errors.push({ field, message: rule.message });
            return;
        }
    });
    
    // 显示错误信息
    if (errors.length > 0) {
        errors.forEach(error => {
            const fieldElement = document.getElementById('student' + error.field.charAt(0).toUpperCase() + error.field.slice(1));
            fieldElement.classList.add('error');
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.textContent = error.message;
            fieldElement.parentNode.appendChild(errorDiv);
        });
        return false;
    }
    
    return true;
}

// 修改保存学生函数
function saveStudent() {
    if (!validateForm()) {
        return;
    }
    
    const studentId = $('#studentId').val();
    const studentData = {
        name: $('#studentName').val(),
        gender: $('#studentGender').val(),
        birthDate: $('#studentBirthDate').val() || null,
        major: $('#studentMajor').val(),
        classNumber: $('#studentClassNumber').val(),
        enrollmentDate: $('#studentEnrollmentDate').val() || null,
        phone: $('#studentPhone').val() || null,
        email: $('#studentEmail').val() || null,
        address: $('#studentAddress').val() || null
    };
    
    const url = studentId ? `/api/students/${studentId}` : '/api/students';
    const method = studentId ? 'PUT' : 'POST';
    
    $.ajax({
        url: url,
        type: method,
        contentType: 'application/json',
        data: JSON.stringify(studentData),
        success: function(response) {
            if (response.code === 200) {
                showAlert(response.message, 'success');
                closeModal();
                loadStudents(currentPage);
            } else {
                showAlert(response.message, 'danger');
            }
        },
        error: function(xhr) {
            const response = JSON.parse(xhr.responseText);
            showAlert(response.message || '操作失败', 'danger');
        }
    });
}

// 添加实时验证
$(document).ready(function() {
    // 为表单字段添加实时验证
    $('.form-control').on('blur', function() {
        const fieldName = this.id.replace('student', '').toLowerCase();
        if (validationRules[fieldName]) {
            validateField(this, validationRules[fieldName]);
        }
    });
});

function validateField(element, rule) {
    const value = element.value;
    $(element).removeClass('error');
    $(element).siblings('.error-message').remove();
    
    if (rule.required && (!value || value.trim() === '')) {
        showFieldError(element, rule.message);
        return false;
    }
    
    if (value && rule.pattern && !rule.pattern.test(value)) {
        showFieldError(element, rule.message);
        return false;
    }
    
    return true;
}

function showFieldError(element, message) {
    $(element).addClass('error');
    const errorDiv = $('<div class="error-message"></div>').text(message);
    $(element).parent().append(errorDiv);
}

// 删除学生
function deleteStudent(id) {
    if (!confirm('确定要删除这个学生吗？')) {
        return;
    }
    
    $.ajax({
        url: `/api/students/${id}`,
        type: 'DELETE',
        success: function(response) {
            if (response.code === 200) {
                showAlert('删除成功', 'success');
                loadStudents(currentPage);
            } else {
                showAlert('删除失败：' + response.message, 'danger');
            }
        },
        error: function() {
            showAlert('网络错误，请稍后重试', 'danger');
        }
    });
}

// 关闭模态框
function closeModal() {
    $('#studentModal').hide();
}

// 显示提示信息
function showAlert(message, type = 'success') {
    const alertHtml = `
        <div class="alert alert-${type}">
            ${message}
        </div>
    `;
    
    $('#alertContainer').html(alertHtml);
    
    // 3秒后自动隐藏
    setTimeout(function() {
        $('#alertContainer').empty();
    }, 3000);
}

// 显示/隐藏加载状态
function showLoading(show) {
    if (show) {
        $('#loading').show();
        $('#studentTableBody').hide();
    } else {
        $('#loading').hide();
        $('#studentTableBody').show();
    }
}

// 文件上传相关变量
let currentStudent = {
    avatarPath: '',
    idCardPath: '',
    attachments: []
};

// 上传头像
function uploadAvatar() {
    const fileInput = document.getElementById('avatarUpload');
    const file = fileInput.files[0];
    
    if (!file) {
        alert('请选择要上传的头像文件');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', file);
    
    $.ajax({
        url: '/api/files/upload/avatar',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.code === 200) {
                currentStudent.avatarPath = response.data.filePath;
                // 显示预览
                const avatarImg = document.getElementById('avatarImg');
                avatarImg.src = response.data.filePath;
                avatarImg.style.display = 'block';
                alert('头像上传成功');
            } else {
                alert('头像上传失败：' + response.message);
            }
        },
        error: function() {
            alert('头像上传失败，请重试');
        }
    });
}

// 上传身份证件照片
function uploadIdCard() {
    const fileInput = document.getElementById('idCardUpload');
    const file = fileInput.files[0];
    
    if (!file) {
        alert('请选择要上传的身份证件照片');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', file);
    
    $.ajax({
        url: '/api/files/upload/idcard',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.code === 200) {
                currentStudent.idCardPath = response.data.filePath;
                // 显示预览
                const idCardImg = document.getElementById('idCardImg');
                idCardImg.src = response.data.filePath;
                idCardImg.style.display = 'block';
                alert('身份证件照片上传成功');
            } else {
                alert('身份证件照片上传失败：' + response.message);
            }
        },
        error: function() {
            alert('身份证件照片上传失败，请重试');
        }
    });
}

// 上传其他附件
function uploadAttachment() {
    const fileInput = document.getElementById('attachmentUpload');
    const files = fileInput.files;
    
    if (files.length === 0) {
        alert('请选择要上传的附件');
        return;
    }
    
    for (let i = 0; i < files.length; i++) {
        const formData = new FormData();
        formData.append('file', files[i]);
        
        $.ajax({
            url: '/api/files/upload/attachment',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.code === 200) {
                    currentStudent.attachments.push({
                        fileName: response.data.fileName,
                        filePath: response.data.filePath
                    });
                    updateAttachmentList();
                } else {
                    alert('附件上传失败：' + response.message);
                }
            },
            error: function() {
                alert('附件上传失败，请重试');
            }
        });
    }
}

// 更新附件列表显示
function updateAttachmentList() {
    const attachmentList = document.getElementById('attachmentList');
    attachmentList.innerHTML = '';
    
    currentStudent.attachments.forEach((attachment, index) => {
        const attachmentItem = document.createElement('div');
        attachmentItem.className = 'attachment-item';
        attachmentItem.innerHTML = `
            <span>${attachment.fileName}</span>
            <button type="button" class="btn btn-danger btn-xs" onclick="removeAttachment(${index})">删除</button>
        `;
        attachmentList.appendChild(attachmentItem);
    });
}

// 删除附件
function removeAttachment(index) {
    currentStudent.attachments.splice(index, 1);
    updateAttachmentList();
}
// 在student.js中添加辅助函数
function triggerFileSelect(inputId) {
    const fileInput = document.getElementById(inputId);
    if (fileInput) {
        fileInput.click();
    }
}